import {addAddress, deleteById, getUserPhone} from '@mall/api/address'
import router from "@src/router";
import {storeBindingsBehavior} from "mobx-miniprogram-bindings";
import mall from "@src/store/mall";
import base from "@src/store/base";
import {updateAddress} from "@src/api/mall/address";

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: base,
    fields: ['themeColor', 'themeTitleColor']
  }, {
    store: mall,
    fields: ['userLocation'],
    actions: ['parseLocation','deteChooseAddress']
  }],
  data: {
    locationObj: null,
    mode: 'add',
    editAddress: {},
    phone: null,
    userName: '',
    detail: null,
    loading: false,
  },
  methods: {
    onLoad: function (options) {
      let {addressStr, mode} = options

      if (mode === 'edit') {
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.on('form', (data) => {
          let editAddress = data.form
          this.setData({
            editAddress: data.form,
            phone: editAddress.phone,
            userName: editAddress.userName,
            detail: editAddress.detail,
          })
        })
        this.setData({mode: 'edit', title: "编辑地址"})
        return;
      }

      this.setData({ mode: "add", title: "新增地址"})
      if (addressStr) {
        // 传了默认地址过来
        let address = JSON.parse(decodeURIComponent(addressStr))
        this.setData({locationObj: address})
        let lc = {
          latitude: address.latitude,
          longitude: address.longitude
        }
        this.parseLocation(lc).then(res => {
          this.setData({locationObj: res, detail: address.addr})
        })
      }
    },
    onLogin() {
      if (!this.data.locationObj && this.data.mode !== 'edit' && this.data.userLocation) {
        this.setData({
          locationObj: this.data.userLocation
        })
      }
    },
    judgePhone(e){
      let myreg = /^[1][0-9]{10}$/;
      if (!myreg.test(  e.detail.value)) {
        this.setData({phone :""})
        wx.showToast({
          title: "请输入正确的手机号",
          icon: "none",
          duration: 1500
        });
      } else {
      }
      console.log(!myreg.test(  e.detail.value))
    },
    handleDelete() {
      wx.showModal({
        title: "",
        content: "删除该地址",
        confirmText: "删除",
        showCancel: true,
        success: (res) => {
          if (res.confirm) {
            deleteById(this.data.editAddress.id).then(res => {
              this.deteChooseAddress()
              wx.showToast({
                title: '设置成功',
                icon: 'success',
                duration: 2000
              })
              router.back();
            })
          }
        }
      });
    },
    submitAddress(e) {
      let form = e.detail.value
      if (!form.userName) {
        wx.showToast({title: "请输入联系人姓名", icon: 'none', duration: 1500});
        return;
      }
      if (!form.phone) {
        wx.showToast({title: "请输入联系人手机号", icon: 'none', duration: 1500});
        return;
      }
      if (!form.detail) {
        wx.showToast({title: "请输入门牌号", icon: 'none', duration: 1500});
        return;
      }

      if (this.data.mode === 'edit') {
        let data = {};
        if (this.data.locationObj) {
          data = {...this.data.locationObj}
          data['id'] = this.data.editAddress.id;
        } else {
          data = this.data.editAddress;
        }
        data['userName'] = form.userName;
        data['phone'] = form.phone;
        data['detail'] = form.detail;

        updateAddress(data).then(res =>{
          wx.showToast({title: '更新成功', duration: 2000})
          setTimeout(() => {
            router.back()
          }, 1000);
          const eventChannel = this.getOpenerEventChannel();
          if (eventChannel) {
            eventChannel.emit('update');
          }
        })
      } else {
        let data = {
          ...e.detail.value,
          ...this.data.locationObj,
          defaulted: false,
          id: null
        };
        addAddress(data).then(res => {
          if (res.code === 0) {
            wx.showToast({title: '添加成功', duration: 2000})
            setTimeout(() => {
              router.back()
            }, 1000);
            const eventChannel = this.getOpenerEventChannel();
            if (eventChannel) {
              eventChannel.emit('update');
            }
          }
        })
      }
    },
    //获取用户手机号
    getPhoneNumber(e) {
      let data = {
        ivStr: e.detail.iv,
        encryptedData: e.detail.encryptedData
      }
      getUserPhone(data).then(res => {
        if (res.code === 0) {
          this.setData({phone: res.data})
        } else {
          wx.showToast({title: '手机号获取失败,请稍后重试', icon: 'none'})
        }
      })
    },
    openSelectAddress() {
      if (this.data.loading) {
        return;
      }
      this.setData({loading: true})
      setTimeout(()=> {
        this.setData({loading: false})
      }, 600)
      wx.chooseLocation({
        success: (res) => {
          let currentName = res.name
          let lc = {
            latitude: res.latitude,
            longitude: res.longitude
          }
          this.parseLocation(lc).then(parseRes => {
            let detail = currentName
            this.setData({locationObj: parseRes, detail})
          })
        },
        fail: (res) => {
          wx.showModal({
            title: "提示",
            content: "获取定位失败, 需要您授权地理位置权限",
            showCancel: true,
            confirmText: '去授权',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting({
                  success: (authList)=>{
                    if (authList.authSetting["scope.userLocation"]) {
                      this.openSelectAddress();
                    } else {
                      wx.showModal({title: "提示", content: "获取定位失败, 将无法获取具体位置", showCancel: false});
                    }
                  }
                });
              }
            }
          });
        }
      })
    }
  }
})
